package com.qjc.demo.base.map;

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author: qjc
 * @Date: 2020/8/26
 */
public class MapTest {

    public static void main(String[] args) {
        // 线程不安全
        HashMap<String, Object> hashMap = new HashMap<>(16);
        hashMap.put("a", "A");
        hashMap.get("a");
        // 线程安全：使用synchronized
        Hashtable<String, Object> hashtable = new Hashtable<>(16);
        hashtable.put("a", "A");
        hashtable.get("a");
        // 线程安全：使用synchronized
        Map<String, Object> synchronizedMap = Collections.synchronizedMap(new HashMap<>());
        synchronizedMap.put("a", "A");
        synchronizedMap.get("a");
        // 线程安全：JDK1.7用的是Segment（分段锁），JDK1.8用的是synchronized+CAS
        ConcurrentHashMap<String, Object> concurrentHashMap = new ConcurrentHashMap<>(16);
        concurrentHashMap.put("a", "A");
        concurrentHashMap.get("a");
    }

}
